# coding:utf-8

from app.extensions import db
from app.models import BaseModel

from common.wechat_util import generate_wechat_oauth
from .constant import WxMenu


class WechatTemplate(BaseModel):
    """
    created by chenhj at 2017/7/25
    微信模板
    """
    __tablename__ = 'wechat_template'

    # 模板名称
    name = db.Column(
        db.Unicode(128),
        nullable=False, unique=True,
        default=''
    )
    # 模板代码(本系统独立维护的编码)
    code = db.Column(
        db.String(128),
        nullable=False, unique=True,
        default=''
    )
    # 模板编码(微信公众号维护的编码)
    template_code = db.Column(
        db.String(128),
        nullable=False,
        default=''
    )
    # 模板体
    content = db.Column(db.TEXT, nullable=False, default='')
    # 模板参数
    params = db.Column(db.TEXT, default='')


class WechatSendLog(BaseModel):
    """
    created by chenhj at 2017/7/28

    """
    __tablename__ = 'wechat_send_log'

    filter_dict = {
        'user_nickname': (),
        'user_mobile': (),
    }

    user_id = db.Column(db.Integer)
    user_nickname = db.Column(db.String(128), default='', index=True)
    user_mobile = db.Column(db.String(16), default='', index=True)
    openid = db.Column(db.String(128), default='')
    code = db.Column(db.String(128), default='')
    content = db.Column(db.Text, default='')
    url = db.Column(db.Text, default='')


class WechatTag(BaseModel):
    """
    created by chenhj at 2017/8/2
    微信标签管理
    """
    tag_id = db.Column(db.Integer)
    tag_name = db.Column(db.String(128), default='')
    user_count = db.Column(db.Integer, default=0)


class WechatMenu(BaseModel):
    """
    created by chenhj at 2017/8/3
    """
    __tablename__ = 'wxmenu'

    # 如果是子菜单, 则pid存储父menu的id
    pid = db.Column(db.Integer, default=0)
    # 顺序(一级菜单为1-3, 二级菜单为1-5)
    idx = db.Column(db.Integer)
    # 1表示一级菜单, 2表示二级菜单
    level = db.Column(db.Integer, default=1)
    # 类型: 网页, 点击, 小程序等
    type = db.Column(db.String(64))
    name = db.Column(db.String(64), default='')
    # click类型时必填项
    key = db.Column(db.String(128), default='')
    # view/miniprogram类型时必填
    url = db.Column(db.TEXT, default='')
    # 暂时没用上这个字段
    media_id = db.Column(db.String(128), default='')
    # miniprogram类型时必填
    appid = db.Column(db.String(128), default='')
    # miniprogram类型时必填
    pagepath = db.Column(db.TEXT, default='')

    @property
    def level_display(self):
        return {
            1: '一级菜单', 2: '二级菜单'
        }[self.level]

    @property
    def pid_display(self):
        if self.pid == 0:
            return '无'
        p_menu = WechatMenu.get_by_id(self.pid)
        return p_menu.name

    @property
    def type_display(self):
        return WxMenu(self.type).display

    @classmethod
    def generate_json(cls):
        """
        created by chenhj at 2017/8/3
        返回微信创建菜单的json结构
        """
        def gen_menu_info(menu):
            """
            created by chenhj at 2017/8/3

            """
            menu_info = {
                'name': menu.name,
            }
            if menu.type != WxMenu.PARENT_BUTTON.value:
                menu_info['type'] = menu.type
                if menu.type == WxMenu.VIEW.value:
                    oauth = generate_wechat_oauth(menu.url)
                    menu_info['url'] = oauth.authorize_url
                elif menu.type == WxMenu.CLICK.value:
                    menu_info['key'] = menu.key
                else:
                    menu_info['url'] = menu.url
                    menu_info['appid'] = menu.appid
                    menu_info['pagepath'] = menu.pagepath
            return menu_info

        ret = {
            'button': []
        }
        menus = cls.query.filter(
            cls.pid == 0,
            cls.deleted_at == 0
        ).order_by(cls.idx)
        # 一级菜单
        for menu in menus:
            menu_info = gen_menu_info(menu)
            # 二级菜单
            if menu.type == WxMenu.PARENT_BUTTON.value:
                menu_info['sub_button'] = []
                sub_menus = cls.query.filter(
                    cls.pid == menu.id,
                    cls.deleted_at == 0
                ).order_by(cls.idx)
                for sub_menu in sub_menus:
                    sub_menu_info = gen_menu_info(sub_menu)
                    menu_info['sub_button'].append(sub_menu_info)
            ret['button'].append(menu_info)
        return ret
